<template>
  <div class="admin-login-page">
    <div class="login-container">
      <div class="login-card">
        <div class="card-header">
          <h1 class="title">관리자 로그인</h1>
          <p class="subtitle">한국 금융 시스템 관리자</p>
        </div>
        
        <el-form 
          :model="loginForm" 
          :rules="loginRules"
          ref="loginFormRef"
          class="login-form"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="관리자 아이디 또는 주민등록번호"
              size="large"
              :prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="비밀번호"
              size="large"
              :prefix-icon="Lock"
              show-password
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              size="large" 
              class="login-btn"
              :loading="isLoading"
              @click="handleLogin"
            >
              {{ isLoading ? '로그인 중...' : '로그인' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { request, type ApiResponse } from '@/utils/request'

// 登录响应数据类型
interface LoginResponseData {
  user: {
    id: number
    username: string
    name: string
    role: string
    status?: string
  }
  token: string
  userType: 'ADMIN' | 'USER'
}

const router = useRouter()
const loginFormRef = ref<InstanceType<typeof ElForm>>()
const isLoading = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '아이디를 입력해 주세요', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '비밀번호를 입력해 주세요', trigger: 'blur' },
    { min: 6, message: '비밀번호는 최소 6자 이상이어야 합니다', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    isLoading.value = true

    const response: any = await request.post('/api/admin/auth/login', {
      username: loginForm.username,
      password: loginForm.password
    })

    if (response.success) {
      // 관리자 토큰 저장
      localStorage.setItem('admin_token', response.data.token)

      // 사용자 정보 저장 (관리자 또는 추천인)
      localStorage.setItem('admin_user', JSON.stringify(response.data.user))
      localStorage.setItem('admin_user_type', response.data.userType)

      ElMessage.success(`다시 오신 것을 환영합니다, ${response.data.user.name}님!`)

      // 根据用户类型跳转到不同页面
      if (response.data.userType === 'ADMIN') {
        router.push('/dashboard')
      } else {
        router.push('/member-login')
      }
    }
  } catch (error: any) {
    console.error('로그인 실패:', error)
    // 오류 메시지는 요청 인터셉터에서 처리됩니다
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped lang="scss">
.admin-login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
}

.login-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  
  .card-header {
    text-align: center;
    margin-bottom: 40px;
    
    .title {
      font-size: 28px;
      font-weight: 700;
      color: #1a202c;
      margin: 0 0 8px 0;
    }
    
    .subtitle {
      font-size: 14px;
      color: #64748b;
      margin: 0;
    }
  }
  
  .login-form {
    .el-form-item {
      margin-bottom: 24px;
    }

    .login-btn {
      width: 100%;
      height: 48px;
      font-size: 16px;
      font-weight: 600;
    }
  }
}

@media (max-width: 480px) {
  .admin-login-page {
    padding: 16px;
  }
  
  .login-card {
    padding: 24px;
    
    .card-header {
      margin-bottom: 32px;
    }
  }
}
</style>
